<?php
class Plus_Model_User_Mapper
{
	protected $_dbTable;
	
	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gatewat provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
	
	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Default_Model_DbTable_User');
		}
		return $this->_dbTable;
	}
	
	public function save(Default_Model_User $user)
	{
		$data = array(
			'id_user' => $user->getId(),
			'login' => $user->getLogin(),
			'email' => $user->getEmail(),
			'password' => $user->getPassword(),
			'id_country' => $user->getIdCountry(),
			'bad_login_counter' => $user->getBadLoginCounter(),
			'last_login_time' => $user->getLastLoginTime(),
			'id_user_privilage' => $user->getIdUserPrivilage,
			'date_created' => $user->getDateCreated()
		);
		
		if (null === ($id = $user->getId())) {
			unset($data['id']);
			$this->getDbTable->insert($data);
		} else {
			$this->getDbTable()->update($data, array('id = ?' => $id));
		}
	}
	
	public function find($id, Plus_Model_User_User $user)
	{
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$user->setId($row->id_user)
			->setLogin($row->login)
			->setEmail($row->email)
			->setPassword($row->password)
			->setIdCountry($row->id_country)
			->setBadLoginCounter($row->bad_login_counter)
			->setLastLoginTime($row->last_login_time)
			->setIdUserPrivilage($row->id_user_privilage)
			->setDateCreated($row->date_created);
	}
	
	public function fetchAll()
	{
		$resultSet = $this->getDbTable()->fetchAll();
		$entries = array();
		foreach ($resultSet as $row) {
			$entry = new Default_Model_User_User();
			$entry->setId($row->id_user)
				->setLogin($row->login)
				->setEmail($row->email)
				->setPassword($row->password)
				->setIdCountry($row->id_country)
				->setBadLoginCounter($row->bad_login_counter)
				->setLastLoginTime($row->last_login_time)
				->setIdUserPrivilage($row->id_user_privilage)
				->setDateCreated($row->date_created)
				->setMapper($this);
			$entries[] = $entry;
		}
		return $entries;
	}
}